# -*- coding:utf8 -*-
import sys
import threading
import time

import feedparser
from Data import bot


def rss2dc(self):
    """
        rss2dc("адрес к RSS ленте")
        Чтение RSS ленты, проверка\отправка новые сообщение.
    """
    try:
        while 1:
            print time.strftime("%Y-%m-%d %H:%M:%S") + ' -> checkup'
            d = feedparser.parse(config['rss'])

            s_rss = []
            s_old = []

            file = open("Data/temp.dat", "r")
            for line in file.readlines():
                s_old.append(line)
            file.close()

            for entry in d.entries:
                s_rss.append(entry.link.encode(config['coding_rss']) + "\n")

            i = 0
            for item in s_rss:
                if (item in s_old) == False:
                    text = (config['text_message']).replace('%url', item).replace('%title', d.entries[i].title).replace('%n',"\n")
                    t.sendmessage(text)
                    time.sleep(1)
                i = i + 1

            file = open("Data/temp.dat", "w")
            for entry in d.entries:
                print >> file, entry.link.encode(config['coding_rss'])
            file.close()

            time.sleep(config['time'])
    except:
        print "Error rss2dc"
        sys.exit(0)

def runbot(self, config):
    """
        Запуск экземляра бота, с передачей ему конфига
    """
    try:
        global t
        t = bot.pyminidcbot(config)
        t.run() # запускаем бота
    except:
        print "Error runbot"
        sys.exit(0)


def loadConfig():
    """
        Загрузка конфига.
    """
    import ConfigParser
    config_dict = {}
    config = ConfigParser.ConfigParser()
    config.read('Data/config.ini')
    config_dict = {
        'host': config.get('connect', 'HOST'),
        'port': int(config.get('connect', 'PORT')),
        'nick': config.get('connect', 'nick'),
        'password': config.get('connect', 'password'),
        'rss': config.get('connect', 'rss'),
        'time': int(config.get('connect', 'time')),
        'coding_hub': config.get('connect', 'coding_hub'),
        'coding_rss': config.get('connect', 'coding_rss'),
        'text_message': unicode(config.get('connect', 'text_message'),"utf8")
    }
    return config_dict

config = loadConfig()

thread_dcbot = threading.Thread(target=runbot, name="t1", args=["self", config])
thread_checkuprss = threading.Thread(target=rss2dc, name="t2", args=["self"])
try:
    thread_dcbot.start()
except:
    print "error run thread runbot"
    sys.exit(0)
time.sleep(5)
thread_checkuprss.start()